package ru.rchervot.sanasar.client.view;

import ru.rchervot.sanasar.client.event.EventPageChange;
import ru.rchervot.sanasar.client.event.EventResultsItem;
import ru.rchervot.sanasar.client.event.HandlerPageChange;
import ru.rchervot.sanasar.client.event.HandlerResultsItem;
import ru.rchervot.sanasar.client.model.ItemObject;
import ru.rchervot.sanasar.client.model.SearchResultsItem;
import ru.rchervot.sanasar.client.rpc.GetItem;
import ru.rchervot.sanasar.client.rpc.GotItem;
import ru.rchervot.sanasar.client.rpc.RPCServiceAsync;

import com.google.gwt.event.shared.HandlerManager;


public abstract class AbstractRecordPresenter implements RecordPresenter {
	
	protected final HandlerManager eventBus;
	protected final RPCServiceAsync service;
	protected final Display display;
	
	AbstractRecordPresenter(Display display, HandlerManager eventBus,
			RPCServiceAsync service) {
		this.display = display;
		this.eventBus = eventBus;
		this.service = service;
		
		listenForItemChange();
		listenForPageChange();
	}
	
	@Override
	public void bindDisplay() {
		display.setPresenter(this);
	}
	
	private void listenForItemChange() {
		eventBus.addHandler(EventResultsItem.getType(),
				new HandlerResultsItem<ItemObject>() {
			@Override
			public void onNewResultsItem(
					EventResultsItem<ItemObject> event) {
				if (event.getItem().isEmpty()) {
					display.showEmptyItem();
				} else {
					display.showItem(event.getItem().getItemView());					
				}
			}
		});
	}
	
	private void listenForPageChange() {
		eventBus.addHandler(EventPageChange.getType(),
				new HandlerPageChange<SearchResultsItem>() {
			@Override
			public void onPageChange(EventPageChange<SearchResultsItem> event) {
			  // on page change ask for new item to display
				// and show empty page until item comes
				display.showEmptyItem();
				
				if (event.isStartPage()) {
					// view would be set invisible by parent view
				} else {
					if (event.getPage().isEmpty()) {
						// view would be set invisible by parent view
					} else {
						service.execute(new GetItem(event.getPage().getQueryID(), 
								event.getPage().getOffset()),
								new GotItem<ItemObject>() {
							public void got(ItemObject item) {
							}
						});					
					}
				}
			}
		});
	}
	
}
